package org.kinglone.weixin.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.kinglone.back.user.model.WeixinUser;
import org.kinglone.back.user.service.WeixinUserService;
import org.kinglone.utlis.StringUtil;
import org.kinglone.weixin.kit.RefreshAccessTokenKit;
import org.kinglone.weixin.kit.SecurityKit;
import org.kinglone.weixin.kit.WeixinBasicKit;
import org.kinglone.weixin.model.WeixinFinalValue;
import org.kinglone.weixin.servlet.WeixinContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;



@Controller
public class WeixinTest {

	@Autowired
	private WeixinUserService weixinUserService;
	
	@RequestMapping("/index.jspx")
	public void index(HttpServletRequest request,HttpServletResponse response) throws IOException{

	//	String path = "http://1n723r6757.iok.la:27693/weixin/getCode.jspx";
		String path = "http://530935ff.all123.net/weixin/getCode.jspx";
		String uri = WeixinFinalValue.AUTH_URL;
		 uri = uri.replace("APPID", WeixinContext.getInstance().getAppId())
		   .replace("REDIRECT_URI",URLEncoder.encode(path, "UTF-8"))
		   .replace("SCOPE", "snsapi_userinfo")
		   .replace("STATE", "1");
		 System.out.println("uri:"+uri); 
		 StringBuffer pageCode=new StringBuffer();
		 pageCode.append("<script>window.location.href='"+uri+"';</script>");
		 response.setContentType("text/html;charset=utf-8");
		 PrintWriter out=response.getWriter();
		 out.println(pageCode.toString());
		 out.flush();
		 out.close();		
	}
	/**
	 * 微信授权-获取用户信息-微信分享朋友圈
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/getCode.jspx")
	public String getCode(HttpServletRequest request,Model model){
		try {
			String code = request.getParameter("code");	
			System.out.println("code:"+code);
			if(StringUtil.isNullOrEmpty(code)){
				return "user/index";
			}
			//get请求根据code获取access_token和openid
			String accessTokenUrl = WeixinFinalValue.AUTH_GET_OID;
			accessTokenUrl = accessTokenUrl.replace("APPID", WeixinContext.getInstance().getAppId()).replace("SECRET",WeixinContext.getInstance().getAppSecurt()).replace("CODE", code);			
			String content = WeixinBasicKit.sendGet(accessTokenUrl);
			JSONObject jsonObject = JSONObject.fromObject(content);
			String	access_token = jsonObject.getString("access_token");			
			String	openid = jsonObject.getString("openid");
			//get请求根据access_token和openid获取用户信息	
			String userInfoUrl =WeixinFinalValue.AUTH_USER_INFO;
			userInfoUrl =userInfoUrl.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);	
			String userCon = WeixinBasicKit.sendGet(userInfoUrl);
			JSONObject userJson = JSONObject.fromObject(userCon);
			//将openid存到session中
			request.getSession().setAttribute("openid", userJson.getString("openid"));
			//根据openid获取用户，如果不存在保存到数据库中
			WeixinUser user = weixinUserService.findUserByOpenid(userJson.getString("openid"));
			if(user == null){
				user = new WeixinUser();
				user.setOpenid(userJson.getString("openid"));
				user.setNickname(userJson.getString("nickname"));
				user.setCity(userJson.getString("city"));
				user.setSex(userJson.getInt("sex"));
				user.setCountry(userJson.getString("country"));
				user.setLanguage(userJson.getString("language"));
				user.setProvince(userJson.getString("province"));
				user.setHeadimgurl(userJson.getString("headimgurl"));
				weixinUserService.save(user);
			}				
			//判断基础access_token是否存在
			String baseAccess_token = RefreshAccessTokenKit.refreshToken();			
			//根据基础的access_token发送get请求获取jsapi_ticket(公众号用于调用微信JS接口的临时票据)从而生成JS-SDK权限验证的签名
			String ticketUrl =WeixinFinalValue.JSAPI_TICKET;
			ticketUrl = ticketUrl.replace("ACCESS_TOKEN", baseAccess_token);
			String ticketCon = WeixinBasicKit.sendGet(ticketUrl);
			JSONObject AccJson = JSONObject.fromObject(ticketCon);
			//签名算法
			String jsapi_ticket = AccJson.getString("ticket");
			String noncestr = "asdw387dy832";
			long timestamp = (long)System.currentTimeMillis()/1000;
			String url = request.getScheme() //当前链接使用的协议
				    +"://" + request.getServerName()//服务器地址 
				    + request.getContextPath() //应用名称，如果应用名称为
				    + request.getServletPath() //请求的相对url 
				    + "?" + request.getQueryString(); //请求参数
			System.out.println(url);
			
			Map<String,String> params = new HashMap<String,String>();
			params.put("jsapi_ticket", jsapi_ticket);
			params.put("noncestr", noncestr);
			params.put("timestamp", String.valueOf(timestamp));
			params.put("url", url);
			
			String string1 = SecurityKit.getString1(params);//排序	
			String signature = SecurityKit.sha1(string1);//加密
			System.out.println("-----signature:"+signature);
			
			model.addAttribute("appId", WeixinContext.getInstance().getAppId());
			model.addAttribute("timestamp", timestamp);
			model.addAttribute("nonceStr", noncestr);
			model.addAttribute("signature", signature);
		} catch (Exception e) {
			e.printStackTrace();
			return "user/index";
		}	
		
		return "user/success";	

	}
	
}
